/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 */
package cn.com.yang.controller;

import javax.annotation.PostConstruct;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;

/**
 * @Model cn.com.yang.controller.TestMetricsController
 * @Desc  metrics demo
 * @author yangyijin
 * @since 2025年4月14日-下午4:04:16
 */
@RestController
public class TestMetricsController {
	private MeterRegistry meterRegistry;
    
    // 计数器
    private Counter requestCounter;
    
    // 计时器
    private Timer requestTimer;
    
    public TestMetricsController(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        // 初始化计数器
        this.requestCounter = Counter.builder("app.request.count")
                .description("请求计数器")
                .tag("controller", "example")
                .register(meterRegistry);
                
        // 初始化计时器
        this.requestTimer = Timer.builder("app.request.time")
                .description("请求处理时间")
                .tag("controller", "example")
                .register(meterRegistry);
    }
    
    @GetMapping("/example")
    public String example() {
        // 增加计数
        requestCounter.increment();
        
        // 记录执行时间
        return requestTimer.record(() -> {
            // 业务逻辑
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "Hello World";
        });
    }
    
    // 使用 Gauge 监控值
    @PostConstruct
    public void init() {
        Gauge.builder("app.queue.size", this, TestMetricsController::getQueueSize)
                .description("队列大小")
                .register(meterRegistry);
    }
    
    private int getQueueSize() {
        // 返回要监控的值
        return 10;
    }
}
